﻿
package com.zhbit.DB;

import java.sql.*;
import java.util.List;

import javax.swing.JOptionPane;
/**
 * 连接数据库，封装对数据库操作的方法
 * @author ZWZ <ZHBIT at 2998732468@qq.com>
 */
public class dbCon {
    	/*
	 * 数据库的驱动类名称
	 */
	private static final String Driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
	/*
	 * 数据库的命名
	 */
	private static final String url = "jdbc:sqlserver://localhost:1433;databaseName=BookDB;user=sa;password=zwz52077051";
	/*
	 * 资源对象
	 */
	private static Connection connection = null; 
	private static Statement statement = null;
	private static ResultSet resultSet = null;
	
	public static Connection getCon() {
		// 数据库的桥接
		try {
			System.out.println("1");
			Class.forName(Driver);
			System.out.println("2"); 
			connection = DriverManager.getConnection(url);
			 System.out.println("3");
			System.out.println("连接数据库成功！");
			return connection;
		} catch (ClassNotFoundException | SQLException e) {
			System.out.println("数据库连接失败！");
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, e.getMessage());
		}
		return null;
	}
    /** 
     * 创建数据库查询
     * @param sql SQL语句 
     * @param params 参数数组，若没有参数则为null 
     * @return 结果集 
     */  
    public static ResultSet executeQueryRS(String sql, Object[] params) {  
    	if (connection == null)
    		return null;
    	try {
			statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, 
					ResultSet.CONCUR_UPDATABLE);
			resultSet = statement.executeQuery(sql);
		} catch (SQLException e) {
			JOptionPane.showMessageDialog(null,e.getMessage());
			e.printStackTrace();
		}
        return resultSet;  
    }  
    // 插入数据库
	public static boolean insertDB(String sql, Object[] params) {
		boolean flag = false;
		try {
			statement = connection.createStatement();
			if (statement.executeUpdate(sql) > 0)
				flag = true;
		} catch (SQLException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, e.getMessage());
			return false;
		}
		return flag;
	}
	// 更新数据库
	public static boolean updateDB(String sql, Object[] params) {
		return insertDB(sql, params);
	}
	// 删除数据库
	public static boolean delete(String sql, Object[] params) {
		return insertDB(sql, params);
	}

	/*
	 * 实现数据库的对象的所有方法的关闭
	 */
	public static void closeAllMethod() {
		try {
			if (resultSet != null) {
				resultSet.close();
			}
			if (statement != null) {
				statement.close();
			}
			if (connection != null) {
				connection.close();
			} else {
				System.out.println("数据库已经关闭！");
			}
		} catch (SQLException e) {
			e.printStackTrace();
			e.getMessage();
		}
	}
}
